<?php

namespace app\api\model\service;

use think\Db;
use think\Model;
use traits\model\SoftDelete;
class Shop extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'service_shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    /**
     * 获取商户列表
     * @param $get
     * @return bool|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function searchShop($get)
    {
        extract($get);
        $lng = $get['lng'];
        $lat = $get['lat'];
        $orderBy = 'distance asc';
        $earth = 6378.137;
        $pi = 3.1415926535898;
        $where['state'] = 1;
        if(isset($city) && $city != '')
        {
            $where['city'] = $city;
        }
        if (isset($name) && $name != '') {
            $where['name|abbr'] = ['like', "%$name%"];
        }
        if(isset($category_id) && $category_id != '')
        {
            $where[] =['exp',Db::raw("FIND_IN_SET('$category_id',category_ids)")];
        }
        $list = self::where($where)
            ->field("id,user_id,name,abbr,logo_image,category_ids,goods_ids,city,district,address,lng,lat,city,trade_hour,(2*$earth*ASIN(SQRT(POW(SIN($pi*(".$lat."-lat)/360),2)+COS($pi*".$lat."/180)*COS(lat*$pi/180)*POW(SIN($pi*(".$lng."-lng)/360),2)))) as distance")
            ->order($orderBy)
            ->page($get['page'])
            ->limit(10)
            ->select();
        foreach ($list as &$value)
        {
            $value['categoryname'] = (new Category())->getCategoryList($value['category_ids']);
            $value['followNum'] = Follow::getCount(['follow_id'=>$value['id'],'state'=>1]);
            $value['commentScore'] = Comment::getCommentScore(['shop_id'=>$value['id'],'state'=>1]);
            $value['goodsList'] = Goods::getNewShopGoods($value['goods_ids']);
        }
        return $list;
    }

    public static function getShop($id)
    {
        return self::where(['id'=>$id,'state'=>1])->field('id,credit_code,to_shop,name,abbr,type,code,intro,logo_image,leader_mobile,leader_name,province,city,district,address,lng,lat,trade_hour')->find();
    }

    public static function getShopDetail($params)
    {
        return self::where(['id'=>$params['id'],'state'=>1])->field('id,to_shop,name,abbr,code,intro,logo_image,leader_mobile,leader_name,province,city,district,address,lng,lat,trade_hour')->find();;
    }

    public static function updateShopGoodsIds($shop_user_id,$ids)
    {
        $shop_id = self::where('user_id',$shop_user_id)->value('id');
        $shopGoods = Goods::where('shop_id',$shop_id)->column('id');
        if(!$shopGoods){
            return $ids;
        }
        return implode(',',$shopGoods).','.$ids;
    }


    public static function getShopTime()
    {
        $minute = date("i");
        $currentTime = time(); // 获取当前时间戳
        $nearestHour = ceil($currentTime / 3600) * 3600;
        $nearTime = ($minute>=0 && $minute<31)?$nearestHour:$nearestHour+1800;
        $data = ['id'=>'','starttime'=>$nearTime];
        return $data;
    }


    public static function getShopInfo($params)
    {
        $shop = self::where(['id'=>$params['id'],'state'=>1])->field('id,to_shop,name,abbr,type,code,intro,logo_image,leader_mobile,leader_name,category_ids,province,city,district,trade_hour,address,lng,lat')->find();
        if(!$shop)
        {
            return false;
        }
        $shop['distance'] = \addons\service\library\Common::distance($params['lng'],$params['lat'],$shop['lng'],$shop['lat']);
        $shop['categoryname'] = (new Category())->getCategoryList($shop['category_ids']);
        $shop['commentScore'] = Comment::getCommentScore(['shop_id'=>$shop['id'],'state'=>1]);
        return $shop;
    }

    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $shop = self::where('user_id',$user_id)->lock(true)->find();
            if ($shop && $money != 0) {
                $before = $shop->ensure_price;
                $after = function_exists('bcadd') ? bcadd($shop->ensure_price, $money, 2) : $shop->ensure_price + $money;
                //更新会员信息
                $shop->save(['ensure_price' => $after]);
                //写入日志
                EnsureLog::create(['user_id' => $user_id, 'money' => $money, 'type'=>1, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }


    /**
     * 返回商家姓名
     * @param $id
     * @return float|mixed|string
     */
    public static function getName($id)
    {
        return self::where(['id'=>$id])->value('abbr');
    }

    public static function getSettleDay($id)
    {
        return self::where(['id'=>$id])->value('settle_day');
    }


}